package com.huitone.gddw.log;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.service.system.ISmLogService;
import com.huitone.gddw.utils.ContextHolderUtils;
import com.huitone.gddw.utils.SysLoginUtil;

import net.sf.json.JSONArray;

/**
 * 日志处理
 * @author wuluodan
 *
 */
@Aspect
@Component
public class LogAspect {

	private static final Logger LOGGER = Logger.getLogger(LogAspect.class);

	@Autowired
	private ISmLogService smLogService;

	@Pointcut("@annotation(com.huitone.gddw.log.Log)")
	public void logCut() {}

	@Around("logCut()")
	public Object doAround(ProceedingJoinPoint point) throws Throwable {
		try {
			// 获取拦截的方法名
	        Signature sig = point.getSignature();
	        MethodSignature msig = null;
	        if (!(sig instanceof MethodSignature)) {
	            throw new IllegalArgumentException("该注解只能用于方法");
	        }
	        msig = (MethodSignature)sig;
	        Object target = point.getTarget();
	        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
	        long startTime = new Date().getTime();
	        
	        // 先执行业务
			Object result = point.proceed();
			
			long endTime = new Date().getTime();
			StringBuilder sb = new StringBuilder();
			sb.append("-------------------- ")
				.append(target.getClass().getSimpleName())
				.append(".")
				.append(currentMethod.getName() + "()")
				.append(" --> ")
				.append(endTime + " - " + startTime + " = " + (endTime - startTime) + "ms")
				.append(" --------------------");
			System.out.println(sb.toString());

	        // 获取操作名称
	        Log annotation = currentMethod.getAnnotation(Log.class);

	        HttpServletRequest request = ContextHolderUtils.getRequest();
	        String loginUserId = SysLoginUtil.getLoginUserId();
	        String userId = loginUserId == null ? request.getParameter("userId") : loginUserId;
	        
	        LogResult logResult = (LogResult)request.getAttribute("logResult");
	        LogResult logMsg = LogResult.SUCCESS;
	        String resultS = JSONArray.fromObject(result).toString();
	        if (logResult != null) {
	        	if (logResult == LogResult.EXCEPTION) {
	        		logResult = LogResult.FAIL;
	        		logMsg = LogResult.EXCEPTION;
	        	}
	        } else if (result.toString().contains("isSuccess=false") || resultS.toString().contains("\"success\":false")) {
	    		logResult = LogResult.FAIL;
	    		logMsg = LogResult.FAIL;
	    	} else {
	    		logResult = LogResult.SUCCESS;
	    		logMsg = LogResult.SUCCESS;
	    	}
	        
	    	SmLog smLog = new SmLog();
	    	smLog.setLogType(annotation.logType().getCode());
	    	smLog.setContent("["+ userId +"]" + annotation.content() + "-" + logMsg.getMsg());
	    	smLog.setResult(logResult.getCode());
			smLogService.save(smLog);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
